var express = require('express');
var router = express.Router();
var UsrModel = require("../model/Usr");
var GoodsModel = require("../model/Goods");
var multiparty = require("multiparty");
//var MongoClient = require("mongodb").MongoClient;

//var DB_CONN_STR = 'mongodb://localhost:27017/h1723';
//var collection = func

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
router.get('/login', function(req, res, next) {
  res.render('login', { title: '登录' });
});

router.get('/list_page1', function(req, res, next) {
  res.render('list_page1', {  });
});

router.get('/list_page2', function(req, res, next) {
  res.render('list_page2', {  });
});

//登录信息
router.post('/api/login4ajax', function(req, res, next) {
	var usrname = req.body.usrname;
	var psw = req.body.psw;
	console.log(usrname,psw)
	var result = {
		code: 1,
		message: "登录成功"
	};
	UsrModel.find({usrname: usrname, psw:psw}, (err, docs)=>{
		if(docs.length == 0) {
			console.log(usrname,psw)
			console.log(docs)
			result.code = -101;
			result.message = "您的账号或密码错误。请重新登录。"
		} else {
			// 登录成功的时候，生成session
			req.session.usrname = usrname;
			console.log(req.session);
		}
		res.json(result);
		//res.send("aaa")
	})
})

//商品信息
router.post('/api/goods', function(req, res, next) {
	var form = new multiparty.Form({
		uploadDir: "public/images"
	});
	var result = {
		code: 1,
		message: "商品信息保存成功"
	};
	form.parse(req, function(err, body, files){
		if(err) {
			console.log(err);
		}
		console.log(body);
		var goods_name = body.goods_name[0];
		var price = body.price[0];
		var imgPath = files["img"][0].path.replace("public\\", "");
		var gm = new GoodsModel();
		gm.goods_name = goods_name;
		gm.price = price;
		gm.imgPath = imgPath;
		gm.save(function(err){
			if(err) {
				result.code = -99;
				result.message = "商品保存失败";
			}
			res.json(result);
		})
	})
});

router.get('/list', function(req, res, next) {
	//判断用户是否登录，如果没登录跳转到login页面。
	console.log(req.session);
	if(req.session == null || req.session.usrname == null) {
		res.render('login', { title: '登录页面' });
		res.redirect("/login"); // 重定向
		return;
	}
		res.render('list', {title:'商品管理'});
	
});

router.post('/api/goods_find', function(req, res, next) {

	GoodsModel.find(function (err, docs) {
		var doc = docs.length;
		var docs = docs;
		console.log(docs);
		if(doc > 0) {
			
			
				res.json(docs);
				//console.log(docs[i]);
		}
			
		
	});
});
module.exports = router;
